package com.gwz.shelf.controller.auth;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.lang.tree.Tree;
import com.gwz.shelf.consts.RedisKeyConst;
import com.gwz.shelf.entity.auth.bo.Permission;
import com.gwz.shelf.entity.auth.bo.Users;
import com.gwz.shelf.entity.auth.dto.ActiveUser;
import com.gwz.shelf.entity.auth.dto.RegisterUser;
import com.gwz.shelf.entity.auth.vo.ImgCode;
import com.gwz.shelf.entity.auth.vo.LoginRes;
import com.gwz.shelf.service.ModulesService;
import com.gwz.shelf.service.PermissionService;
import com.gwz.shelf.service.UsersService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/api/auth")
@Slf4j
@Api(tags = {"权限模块"})
public class AuthController {
    @Autowired
    private UsersService usersService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ModulesService modulesService;
    @Autowired
    private PermissionService permissionService;

    /**
     * 注册
     */
    @PostMapping("/register")
    @ApiOperation(value = "注册", hidden = true)
    public void register(@RequestBody @Validated RegisterUser registerUser) {
        Users users = new Users();
        users.setLoginName(registerUser.getName());
        users.setPassword(registerUser.getPassword());
        usersService.save(users);
    }

    /**
     * 登录
     */
    @PostMapping("/login")
    @ApiOperation(value = "登录", responseContainer = "token", responseReference = "token")
    public LoginRes login(@RequestBody @Validated RegisterUser registerUser) {
        if (redisTemplate.hasKey(RedisKeyConst.IMG_CODE + registerUser.getImgId())) {
            throw new IllegalArgumentException("验证码过期:");
        }
        Object imgCode = redisTemplate.opsForValue().get(RedisKeyConst.IMG_CODE + registerUser.getImgId());
        if (!registerUser.getImgCode().equals(imgCode))
            throw new IllegalArgumentException("验证码错误:");

        Users users = usersService.lambdaQuery().eq(Users::getLoginName, registerUser.getName()).last("limit 1").one();
        if (users == null)
            throw new IllegalArgumentException("未获取到用户:" + registerUser.getName());

        if (!registerUser.getPassword().equals(users.getPassword()))
            throw new IllegalArgumentException("密码错误:" + registerUser.getName());


        List<Tree<String>> modules = modulesService.getModulesByUserId(users.getId());
        List<Permission> permissions = permissionService.getPermissionByUserId(users.getId());


        ActiveUser activeUser=new ActiveUser();
        activeUser.setUsers(users);
        activeUser.setMenu(modules);
        activeUser.setPermissions(permissions);
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(RedisKeyConst.AUTH + token, activeUser);
        LoginRes loginRes = new LoginRes();
        loginRes.setToken(token);
        return loginRes;
    }


    @GetMapping("/imgCode")
    @ApiOperation(value = "获取图形验证码")
    public ImgCode getImgCode() {
        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        String imageBase64 = lineCaptcha.getImageBase64Data();

        String imgId = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(RedisKeyConst.IMG_CODE + imgId, lineCaptcha.getCode());
        log.info("图形验证码:{}", lineCaptcha.getCode());
        ImgCode imgCode = new ImgCode();
        imgCode.setImg(imageBase64);
        imgCode.setImgId(imgId);
        return imgCode;
    }


}
